<template>
    <div>
        <!--        面包屑-->
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/welcom' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>用户管理</el-breadcrumb-item>
            <el-breadcrumb-item>用户列表</el-breadcrumb-item>
        </el-breadcrumb>
        <!--        卡片视图区域-->
        <el-card>
            <el-row :gutter="20">
                <el-col :span="7">
                    <el-input clearable @clear="getUserList" type="text" v-model="queryInfo.query" placeholder="请输入内容">
                        <el-button @click="getUserList" slot="append" icon="el-icon-search"></el-button>
                    </el-input>
                </el-col>
                <el-col :span="4">
                    <el-button type="primary" @click="dialogVisible = true">添加用户</el-button>
                </el-col>
            </el-row>
            <!--            用户列表区域
                            border 表格线
                            stripe 隔行变色效果

                            label 指定当前列的标题
                            prop 指定当前列的数据
            -->
            <el-table :data="userList" border stripe>
                <!--                设置表格的索引列-->
                <el-table-column label="#" type="index"></el-table-column>
                <el-table-column label="姓名" prop="username"></el-table-column>
                <el-table-column label="邮箱" prop="email"></el-table-column>
                <el-table-column label="电话" prop="mobile"></el-table-column>
                <el-table-column label="角色" prop="role_name"></el-table-column>
                <el-table-column label="状态">
                    <!--                    用该标签时，scope.row 就可以获取当前行的所有数据-->
                    <template slot-scope="scope">
                        <el-switch
                                v-model="scope.row.mg_state"
                                :active-value="true"
                                :inactive-value="false"
                                @change="updateUserState(scope.row)"
                                active-color="#13ce66"
                                inactive-color="#ff4949">
                        </el-switch>
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="160px">
                    <template slot-scope="scope">
                        <!--
                        :enterable="false" 表示鼠标不能放到提示框中去
                        circle 将图标变成圆形，默认是方的
                        -->
                        <!--                        修改按钮-->
                        <el-tooltip :enterable="false" class="item" effect="dark" content="编辑用户" placement="top">
                            <el-button size="mini" @click="showEditDialog(scope.row)" type="primary" icon="el-icon-edit"
                                       circle></el-button>
                        </el-tooltip>
                        <!--                        删除按钮-->
                        <el-tooltip :enterable="false" class="item" effect="dark" content="删除用户" placement="top">
                            <el-button size="mini" @click="deleteUser(scope.row)" type="danger" icon="el-icon-delete"
                                       circle></el-button>
                        </el-tooltip>
                        <!--                        分配角色按钮-->
                        <el-tooltip :enterable="false" class="item" effect="dark" content="分配角色" placement="top">
                            <el-button size="mini" type="warning" icon="el-icon-setting" circle></el-button>
                        </el-tooltip>
                    </template>

                </el-table-column>
            </el-table>
            <!--            layout="total, sizes, prev, pager, next, jumper"  用于指定页面上面显示那些组件-->
            <el-pagination
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    :current-page="queryInfo.pagenum"
                    :page-sizes="[1,2,5,10]"
                    :page-size="queryInfo.pagesize"
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="total">
            </el-pagination>
        </el-card>
        <!--        添加用户的对话框区域
        :visible.sync  控制对话框是否显示
        -->
        <el-dialog title="添加用戶" :visible.sync="dialogVisible" width="50%"
                   @close="addDialogClosed">
            <!--添加用户的表单区域-->
            <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="70px">
                <el-form-item label="用户名" prop="username">
                    <el-input v-model="addForm.username" placeholder="请输入用户名"></el-input>
                </el-form-item>

                <el-form-item label="密码" prop="password">
                    <el-input v-model="addForm.password" placeholder="请输入密码"></el-input>
                </el-form-item>

                <el-form-item label="邮箱" prop="email">
                    <el-input v-model="addForm.email" placeholder="请输入邮箱"></el-input>
                </el-form-item>

                <el-form-item label="手机号" prop="mobile">
                    <el-input v-model="addForm.mobile" placeholder="请输入手机号"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
            <el-button @click="dialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="addUser">确 定</el-button>
            </span>
        </el-dialog>

        <!--        编辑用户的对话框-->

        <el-dialog title="编辑用戶" :visible.sync="editDialogVisible" width="50%"
                   @close="editDialogClosed">
            <!--编辑用戶的表单区域-->
            <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="70px">
                <el-form-item label="用户名" prop="username">
                    <el-input v-model="editForm.username" placeholder="请输入用户名" disabled></el-input>
                </el-form-item>

                <el-form-item label="邮箱" prop="email">
                    <el-input v-model="editForm.email" placeholder="请输入邮箱"></el-input>
                </el-form-item>

                <el-form-item label="手机号" prop="mobile">
                    <el-input v-model="editForm.mobile" placeholder="请输入手机号"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
            <el-button @click="editDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="editUser">确 定</el-button>
            </span>
        </el-dialog>

    </div>
</template>

<script>
  export default {
    name: 'Users',
    data () {
      // 验证邮箱规则
      var checkEamil = (rule, value, callback) => {
        const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/
        if (regEmail.test(value)) {
          // 合法邮箱
          return callback()
        } else {
          return callback(new Error('请输入合法的邮箱'))
        }
      }
      // 验证手机号规则
      var checkMobile = (rule, value, callback) => {
        const regMobile = /^[1][3,4,5,6,7,8,9][0-9]{9}$/
        if (regMobile.test(value)) {
          // 合法手机号
          return callback()
        } else {
          return callback(new Error('请输入合法的手机号'))
        }
      }

      let userRules = {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 10, message: '用户名的长度在3~10个字符之间', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 15, message: '密码的长度在6~15个字符之间', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          // 自定义校验规则
          { validator: checkEamil, trigger: ['change', 'blur'] }
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          // 自定义校验规则
          { validator: checkMobile, trigger: 'change' },
          { min: 11, max: 11, message: '手机号长度为11位', trigger: 'blur' }
        ]
      }
      return {
        // 获取用户列表的参数
        queryInfo: {
          query: '',
          pagenum: 1,
          pagesize: 10
        },
        addForm: {
          mobile: '',
          username: '',
          email: '',
          password: ''
        },
        editForm: {},
        addFormRules: userRules,
        editFormRules: userRules,
        userList: [],
        total: 0,
        // 控制添加用户的对话框的显示与否
        dialogVisible: false,
        // 控制修改用户的对话框的显示与否
        editDialogVisible: false
      }
    },
    created () {
      this.getUserList()
    },
    methods: {
      deleteUser (userInfo) {
        // 删除用户
        let _this = this
        _this.$confirm('此操作将永久删除该用户, 是否继续?', '删除用户提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          _this.$http.delete('users/' + userInfo.id)
          _this.$message.success('删除成功')
          _this.getUserList()
        }).catch(() => {
          _this.$message.info('已取消删除')
        })
      },
      // 展示用户编辑的对话框
      showEditDialog (userInfo) {
        this.editForm = userInfo
        this.editDialogVisible = true
      },
      // 关闭添加用户对话框处理的函数
      addDialogClosed () {
        // 重置表单项数据
        this.$refs.addFormRef.resetFields()
      },
      editDialogClosed () {
        this.$refs.editFormRef.resetFields()
      },
      addUser () {
        this.$refs.addFormRef.validate(async valid => {
          if (!valid) {
            return
          }
          // 校验成功，发起请求
          const { data: res } = await this.$http.post('users', this.addForm)
          // 201 状态表示添加成功
          if (res.meta.status !== 201) {
            this.$message.error(res.meta.msg)
          } else {
            this.$message.success(res.meta.msg)

            // 若后端在添加数据时将用户返回了，那么久可以直接向用户数组中添加数据
            // this.userList.push(res.data)

            // 刷新用户列表
            this.getUserList()
            // 若请求成功则将弹框关闭
            this.dialogVisible = false
          }
        })
      },
      editUser () {
        this.$refs.editFormRef.validate(async valid => {
          if (!valid) {
            return
          }
          // 校验成功，发起请求
          const { data: res } = await this.$http.put('users/' + this.editForm.id, this.editForm)
          // 201 状态表示添加成功
          if (res.meta.status !== 200) {
            this.$message.error(res.meta.msg)
          } else {
            this.getUserList()
            this.editDialogVisible = false
            this.$message.success(res.meta.msg)
          }
        })
      },
      // 修改用户状态
      async updateUserState (userInfo) {
        // const { data: res } = await this.$http.put('users/' + userInfo.id + '/state/' + userInfo.mg_state)
        const { data: res } = await this.$http.put(`users/${userInfo.id}/state/${userInfo.mg_state}`)
        if (res.meta.status !== 200) {
          this.$message.error(res.meta.msg)
          userInfo.mg_state = !userInfo.mg_state
          return
        }
        this.$message.success(res.meta.msg)
      },
      // 监听 pageSize 改变的事件
      handleSizeChange (pageSize) {
        this.queryInfo.pagesize = pageSize
        this.getUserList()
      },
      handleCurrentChange (pageNum) {
        this.queryInfo.pagenum = pageNum
        this.getUserList()
      },
      // 获取用户列表
      async getUserList () {
        const { data: res } = await this.$http.get('users', {
          params: this.queryInfo
        })
        if (res.meta.status !== 200) {
          this.$message.error(res.meta.msg)
          return
        }
        this.userList = res.data.users
        this.total = res.data.total
        console.log(this.$data)
      }
    }
  }
</script>

<style scoped lang="less">
</style>
